﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("SCS");

SCS.DialogControl = function (element) {
    SCS.DialogControl.initializeBase(this, [element]);

    /* Fields
    ****************************************************************************************************************/

    // element ids
    this._targetControlId = "";

    // element references
    this._captionControl = null;
    this._contentControl = null;
    this._closeButton = null;
    this._okButton = null;

    // delegates    
    this._dialogKeypressDelegate = null;
    this._dialogCloseDelegate = null;
    this._popupUpdatingDelegate = null;
    this._popupUpdatedDelegate = null;
    this._popupShowingDelegate = null;
    this._popupShownDelegate = null;
    this._popupHiddenDelegate = null;
    this._popupHidingDelegate = null;
    this._repositioningDelegate = null;
    this._popupButtonClickedDelegate = null;

    // embedded behaviors
    this._popupBehavior = null;

    // data
    this._clientState = {};
    this._popupProps = {};
    this._passThruData = {};
    this._contentSettings = {};

    // other
    this._selectedButton = 1;
    this._contentUrl = null;
    this._contextKey = null;
};

SCS.DialogControl.prototype = {

    /* Setup
    ****************************************************************************************************************/
    initialize: function () {
        SCS.DialogControl.callBaseMethod(this, 'initialize');

        this._captionControl = this.findControl("caption");
        this._contentControl = this.findControl("content");
        this._closeButton = this.findControl("close");
        this._okButton = this.findControl("ok");

        var targetControl = $get(this._targetControlId);

        if (!targetControl) {

            // add fake targetControl
            this._targetControlId = this.get_id() + "fakeTarget";
            var button = document.createElement("input");
            button.setAttribute("type", "button");
            button.setAttribute("id", this._targetControlId);
            button.setAttribute("style", "display:none");
            this.get_element().appendChild(button);
            targetControl = button;
        }

        this._popupBehavior = $create(SCS.DialogBehavior, this._popupProps, null, null, targetControl);
        var popupBehavior = this._popupBehavior;

        //var js = String.format("var d=$find('{0}');d.set_SelectedButton(", this.get_id());

        popupBehavior.set_OnOkScript( popupBehavior.get_OnOkScript());
        popupBehavior.set_OnCancelScript(popupBehavior.get_OnCancelScript());

        this._popupUpdatingDelegate = Function.createDelegate(this, this.onUpdating);
        popupBehavior.add_populating(this._popupUpdatingDelegate);

        this._popupUpdatedDelegate = Function.createDelegate(this, this.onUpdated);
        popupBehavior.add_populated(this._popupUpdatedDelegate);

        this._popupShowingDelegate = Function.createDelegate(this, this.onShowing);
        popupBehavior.add_showing(this._popupShowingDelegate);

        this._popupShownDelegate = Function.createDelegate(this, this.onShown);
        popupBehavior.add_shown(this._popupShownDelegate);

        this._popupHidingDelegate = Function.createDelegate(this, this.onHiding);
        popupBehavior.add_hiding(this._popupHidingDelegate);

        this._popupHiddenDelegate = Function.createDelegate(this, this.onHidden);
        popupBehavior.add_hidden(this._popupHiddenDelegate);

        this._popupButtonClickedDelegate = Function.createDelegate(this, this.onButtonClicked);
        popupBehavior.add_ButtonClicked(this._popupButtonClickedDelegate);

        this._repositioningDelegate = Function.createDelegate(this, this.onRepositioning);
        this.get_ModalPopupBehavior().add_Repositioning(this._repositioningDelegate);

        if (this._closeButton) {
            this._dialogCloseDelegate = Function.createDelegate(this, this.onClose);
            $addHandler(this._closeButton, "click", this._dialogCloseDelegate);
        }

        if (this._clientState.show)
            this.show();
    },

    /* Teardown
    ****************************************************************************************************************/

    dispose: function () {

        //Sys.Debug.fail("");

        this._captionControl = null;

        var popupBehavior = this._popupBehavior;

        popupBehavior.remove_populating(this._popupUpdatingDelegate);
        this._popupUpdatingDelegate = null;

        popupBehavior.remove_populated(this._popupUpdatedDelegate);
        this._popupUpdatedDelegate = null;

        popupBehavior.remove_showing(this._popupShowingDelegate);
        this._popupShowingDelegate = null;

        popupBehavior.remove_shown(this._popupShownDelegate);
        this._popupShownDelegate = null;

        popupBehavior.remove_hidden(this._popupHiddenDelegate);
        this._popupHiddenDelegate = null;

        this.get_ModalPopupBehavior().remove_Repositioning(this._repositioningDelegate);
        this._repositioningDelegate = null;

        if (this._closeButton) {
            $removeHandler(this._closeButton, "click", this._dialogCloseDelegate);
            this._dialogCloseDelegate = null;
        }

        SCS.DialogControl.callBaseMethod(this, 'dispose');
    },

    /* Events
    *******************************************************************************************************/

    add_Showing: function (handler) {

        this.get_events().addHandler('Showing', handler);
    },
    remove_Showing: function (handler) {

        this.get_events().removeHandler('Showing', handler);
    },
    raiseShowing: function (eventArgs) {

        var handler = this.get_events().getHandler('Showing');
        if (handler)
            handler(this, eventArgs);
    },

    add_Shown: function (handler) {

        this.get_events().addHandler('Shown', handler);
    },
    remove_Shown: function (handler) {

        this.get_events().removeHandler('Shown', handler);
    },
    raiseShown: function (eventArgs) {

        var handler = this.get_events().getHandler('Shown');
        if (handler)
            handler(this, eventArgs);
    },

    add_Hiding: function (handler) {

        this.get_events().addHandler('Hiding', handler);
    },
    remove_Hiding: function (handler) {

        this.get_events().removeHandler('Hiding', handler);
    },
    raiseHiding: function (eventArgs) {

        var handler = this.get_events().getHandler('Hiding');
        if (handler)
            handler(this, eventArgs);
    },

    add_Hidden: function (handler) {

        this.get_events().addHandler('Hidden', handler);
    },
    remove_Hidden: function (handler) {

        this.get_events().removeHandler('Hidden', handler);
    },
    raiseHidden: function (eventArgs) {

        var handler = this.get_events().getHandler('Hidden');
        if (handler)
            handler(this, eventArgs);
    },

    add_Updating: function (handler) {

        this.get_events().addHandler('Updating', handler);
    },
    remove_Updating: function (handler) {

        this.get_events().removeHandler('Updating', handler);
    },
    raiseUpdating: function (eventArgs) {

        //Sys.Debug.fail("");

        var handler = this.get_events().getHandler('Updating');
        if (handler)
            handler(this, eventArgs);

        if (eventArgs.get_cancel())
            this.setContentSettings(this._contentSettings) // restore previous settings
    },

    add_Updated: function (handler) {

        this.get_events().addHandler('Updated', handler);
    },
    remove_Updated: function (handler) {

        this.get_events().removeHandler('Updated', handler);
    },
    raiseUpdated: function (eventArgs) {

        //Sys.Debug.fail("");

        this._contextKey = this._getContextKey();
        this._contentSettings = this.getContentSettings();
        this._updateLayout();

        var handler = this.get_events().getHandler('Updated');
        if (handler)
            handler(this, eventArgs);
    },

    /* Event Handlers
    ****************************************************************************************************************/

    onUpdating: function (sender, args) {

        //Sys.Debug.fail("");

        var cancel,
            popup = this.get_ModalPopupBehavior();

        if (popup.get_dynamicServicePath() != "none") {

            this._popupBehavior._dynamicPopulateBehavior.set_ClearContentsDuringUpdate(false);
            var args = new Sys.CancelEventArgs();
            this.raiseUpdating(args);
            cancel = args.get_cancel();
        }
        else {

            if (this._contentUrl)
                this._populateStatic();

            cancel = true;
        }

        args.set_cancel(cancel);
    },
    onUpdated: function (sender, args) {

        this.raiseUpdated(Sys.EventArgs.Empty);
    },
    onShowing: function (sender, args) {

        this.raiseShowing(args);
    },
    onShown: function (sender, args) {

        this._dialogKeypressDelegate = Function.createDelegate(this, this.onkeypress);
        $addHandler(document, "keypress", this._dialogKeypressDelegate);

        var caption = this.findControl("caption");
        caption.focus();

        this.raiseShown(Sys.EventArgs.Empty);
        this._clientState.show = true
    },
    onHiding: function (sender, args) {

        this.raiseHiding(args);
    },
    onHidden: function (sender, args) {

        if (this._dialogKeypressDelegate) {
            $removeHandler(document, "keypress", this._dialogKeypressDelegate)
            this._dialogKeypressDelegate = null;
        }

        this.raiseHidden(Sys.EventArgs.Empty);
        this._clientState.show = false;
    },
    onButtonClicked: function (sender, args) {

        
    },
    onRepositioning: function (sender, args) {

        //alert("onRepositioning");
    },
    onkeypress: function (e) {

        if (e.charCode == 13) { // enter key

            this.onEnterPressed(e);
        }
        else if (e.charCode == 27) { // escape key

            this.hide();
        }
    },
    onClose: function (e) {

        this._popupBehavior._onCancel(e);
    },

    onEnterPressed: function (e) {

        if (this._okButton) {
            this._popupBehavior._onOk(e);
        }
    },

    //onPropChanged: function (sender, args) {

    //args.get_propertyName();
    //},

    /* Public / Protected Methods
    ****************************************************************************************************************/

    show: function (caption, content) {

        if (content && typeof (content) != "undefined")
            this.set_Content(content);

        if (caption && typeof (caption) != "undefined")
            this.set_Caption(caption);

        this._popupBehavior.show();
    },
    hide: function () {

        this._popupBehavior.hide();
    },
    populate: function (settings) {

        this.setContentSettings(settings);
        this.refresh();
    },
    refresh: function () {

        //Sys.Debug.fail("");
        var popup = this._popupBehavior;

        if (this._contentUrl)
            this._populateStatic();

        else if (popup.get_dynamicServicePath() != "none") {

            if (popup._dynamicPopulateBehavior) {
                Sys.Application.removeComponent(popup._dynamicPopulateBehavior);
                popup._dynamicPopulateBehavior.dispose();
                popup._dynamicPopulateBehavior = null;
            }
            popup.populate();
        }
    },
    getSubmitData: function () {

        return this._passThruData;
    },
    findControl: function (id) {

        var root = this.get_element();

        return $get(root.id + "_" + id, root);
    },
    loadClientState: function (value) {

        this._clientState = Sys.Serialization.JavaScriptSerializer.deserialize(value)
    },
    saveClientState: function () {

        return Sys.Serialization.JavaScriptSerializer.serialize(this._clientState);
    },

    setContentSettings: function (settings) {

        //Sys.Debug.fail("");

        var popup = this.get_ModalPopupBehavior();

        if (typeof (settings.url) != "undefined") {

            this.set_contentUrl(settings.url);
            popup.set_dynamicServicePath("none");
            popup.set_dynamicServiceMethod("none");
            popup.set_dynamicContextKey("none");
        }
        else {
            // only update what has been defined
            //
            if (typeof (settings.servicePath) != "undefined")
                popup.set_dynamicServicePath(settings.servicePath);

            if (typeof (settings.serviceMethod) != "undefined")
                popup.set_dynamicServiceMethod(settings.serviceMethod);

            if (typeof (settings.contextKey) != "undefined") {

                var key = settings.contextKey;
                if (key.startsWith("#"))
                    key = popup.get_dynamicContextKey().split("#")[0] + key;

                popup.set_dynamicContextKey(key);
            }

            this.set_contentUrl(null);
        }
    },

    getContentSettings: function () {

        var popup = this.get_ModalPopupBehavior();

        return {
            url: this._contentUrl,
            servicePath: popup.set_dynamicServicePath(),
            serviceMethod: popup.set_dynamicServiceMethod(),
            contextKey: popup.get_dynamicContextKey()
        };
    },

    /* Private Methods
    ****************************************************************************************************************/

    _populateStatic: function () {

        //Sys.Debug.fail("");

        var args = new Sys.CancelEventArgs();
        this.raiseUpdating(args);

        if (args.get_cancel())
            return;

        var request = new Sys.Net.WebRequest();

        request.set_url(this._contentUrl);
        request.set_httpVerb("GET");
        request.add_completed(Function.createDelegate(this, this._onStaticPopulateComplete));
        request.invoke();
    },

    _onStaticPopulateComplete: function (executor, eventArgs) {

        this._contentControl.innerHTML = (executor.get_responseAvailable())
             ? executor.get_responseData()
             : executor.get_statusText() + " Code: " + executor.get_statusCode();

        this.raiseUpdated(Sys.EventArgs.Empty);
    },

    _updateLayout: function () {

        //Sys.Debug.fail("");

        //var titleFooterHeight = 0;
        //var sections = this.get_element().children;
        //var contentElem = this.get_ContentElement();

        //for (var i = 0; i < sections.length; i++) {

        //    if (sections[i] !== contentElem) {
        //        var bounds = this._getBounds(sections[i]);
        //        titleFooterHeight += bounds.height;
       //    }
        //}

        //contentElem.style.height = ((this._getBounds(this.get_element()).height - titleFooterHeight) - 20) + "px";
    },

    _getContextKey: function () {

        var key,
            url = this.get_contentUrl();

        if (url)
            key = url;
        else {
            var popup = this.get_ModalPopupBehavior();
            key = String.format("{0}:{1}:{2}", popup.get_dynamicServicePath(), popup.get_dynamicServiceMethod(), popup.get_dynamicContextKey());
        }

        return key;
    },

    _getBounds: function (element) {

        return Sys.UI.DomElement.getBounds(element);
    },

    /* Properties
    ****************************************************************************************************************/

    get_Caption: function () {

        return this._captionControl.innerHTML;
    },
    set_Caption: function (value) {

        if (this._captionControl.innerHTML != value) {
            this._captionControl.innerHTML = value;
            this.raisePropertyChanged('Caption');
        }
    },
    get_Content: function () {

        return this._contentControl.innerHTML;
    },
    set_Content: function (value) {

        if (this._contentControl.innerHTML != value) {
            this._contentControl.innerHTML = value;
            this.raisePropertyChanged('Content');
        }
    },
    get_ContentElement: function () {
        return this._contentControl;
    },
    get_contentUrl: function () {
        return this._contentUrl;
    },
    set_contentUrl: function (value) {
        this._contentUrl = value;
    },
    get_targetControlId: function () {
        return this._targetControlId;
    },
    set_targetControlId: function (value) {
        this._targetControlId = value;
    },
    get_clientState: function () {
        return this._clientState;
    },
    get_passThruData: function () {
        return this._passThruData;
    },
    get_modalPopupProperties: function () {
        return this._popupProps;
    },
    get_ModalPopupBehavior: function () {
        return this._popupBehavior;
    },
    get_SelectedButton: function () {
        return this._selectedButton;
    },
    set_SelectedButton: function (value) {
        value = this._selectedButton;
    }
};

/* Registration
****************************************************************************************************************/

SCS.DialogControl.registerClass('SCS.DialogControl', Sys.Extended.UI.ControlBase);

